package user

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/user"
	ServiceAdmin "gq_volunteer_platform/service/admin"
	"gq_volunteer_platform/service/message_queue"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/lluck42/tools"
)

func MyChangeList(c *gin.Context) {

	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		Name           string `binding:"max=255"`
		CheckStatus    string `binding:"oneof='' 待审核 已驳回"`
		ChangeStatus   string `binding:"oneof='' 待审核"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	// 查询
	var count int64
	var list []struct {
		ID                   uint `gorm:"primarykey;->"`
		OrganizationId       uint
		ChangeOrganizationId uint
		Name                 string
		RealName             string
		ProfilePhoto         string
		MobileNumber         string
		LastIp               string
		LastLoginTime        string
		ServeHour            int
		Point                int
		CheckStatus          string
		CheckNote            string
		ChangeStatus         string
		ChangeNote           string
		CreatedAt            string
	}

	var tx = bean.MysqlDb.Model(&user.User{})

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, req.OrganizationId)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	tx = tx.Where("`change_organization_id` in ?", organization_my_ids)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}
	if req.ChangeStatus != "" {
		tx = tx.Where("`change_status`=?", req.ChangeStatus)
	}
	if req.CheckStatus != "" {
		tx = tx.Where("`check_status`=?", req.CheckStatus)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").
		Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func ChangeOrganizationCheck(c *gin.Context) {

	var req struct {
		ID     uint   `binding:"max=10000000"`
		Status string `binding:"oneof='已审核 已驳回"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one user.User

	if err := bean.MysqlDb.Model(&user.User{}).Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("用户不存在id:%d", req.ID))
		return
	}

	// 验证是否有修改权限 只能审核自己组织的成员
	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var two user.User
	two.ID = one.ID
	if req.Status == "已审核" {
		two.OrganizationId = one.ChangeOrganizationId
	}
	if req.Status == "已驳回" {
		two.OrganizationId = one.OrganizationId
	}
	two.ChangeOrganizationId = 0
	two.ChangeStatus = "待申请"

	if err := bean.MysqlDb.Select("organization_id", "change_organization_id", "change_status").Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
	// 发送通知 jldtx
	var user_list struct {
		ID        uint
		Openid    string
		CreatedAt string
	}
	if err := bean.MysqlDb.Unscoped().Model(&user.User{}).Where("`id`=?", one.ID).First(&user_list).Error; err != nil {
		bean.Log.Error(err)
		return
	}

	var timeNowStr = time.Now().Format(time.DateTime)

	var Openid = user_list.Openid
	var page = "pages/user/myOrgList/index"
	var applyProject = "志愿者机构变更申请"
	var applyTime = timeNowStr
	var applyResult = ""
	if req.Status == "已审核" {
		applyResult = "您的申请已通过"
	} else if req.Status == "已驳回" {
		applyResult = "您的申请已驳回"
	}
	if err := message_queue.MessageQueueAddT1(Openid, page, applyProject, applyTime, applyResult); err != nil {
		// 错误记录
		bean.Log.Error(err)
	}
}
